import logging
import os
import re
import shutil

from pyquery import PyQuery
from scrapy.utils.project import get_project_settings

from esgcc.items import CertImageItem

settings = get_project_settings()
logger = logging.getLogger(__name__)


# 解析资质
def parse_cert(response):
    meta = response.meta
    sku_id = meta.get('skuId')
    batch_no = meta.get('batchNo')

    image_urls = list()
    image_paths = list()
    item = CertImageItem()
    item['skuId'] = sku_id
    item['batchNo'] = batch_no

    item['image_urls'] = image_urls
    item['image_paths'] = image_paths

    jpy = PyQuery(response.text)
    links = jpy('div.img_con a')
    for idx, link in enumerate(links.items()):
        file_id = match_file_id(link.attr('href'))
        new_link = 'http://b.esgcc.com.cn/showDetail/downloadAttachmentFile.do?fileId=%s' % file_id

        image_urls.append(new_link)
        image_paths.append('cert/{}/{}/{}-{}.jpg'.format(batch_no, sku_id, sku_id, str(idx)))

    return item


# 从链接中解析证书文件编号
def match_file_id(link):
    # http://b.esgcc.com.cn/showDetail/getOneQualityImage?fileId=EC561259F69D4CFCA332671F7392329A
    if link:
        arr = re.findall(r'fileId=(\w+)', link.strip())
        if len(arr):
            return arr[0].strip()
    return ''


def init_folder(batch_no):
    """
    初始化目录
    :param batch_no:
    :return:
    """
    root = settings.get('IMAGES_STORE')
    dist_dir = root + 'cert/{}'.format(batch_no)
    if not os.path.exists(dist_dir):
        os.makedirs(dist_dir)
        logger.info('创建目录: %s' % dist_dir)


def check_pool_exist(sku_id):
    """
    检查请求图片是否存在
    :param item:
    :return:
    """
    root = settings.get('IMAGES_STORE')
    img_file = root + 'cert/pool/' + sku_id
    if not os.path.exists(img_file):
        return False

    return True


def copy_from_pool(sku_id, batch_no):
    """
    检查请求图片是否存在
    :param item:
    :return:
    """
    root = settings.get('IMAGES_STORE')
    sku_dir = root + 'cert/pool/{}'.format(sku_id)
    dist_dir = root + 'cert/{}/{}'.format(batch_no, sku_id)
    if not os.path.exists(dist_dir):
        shutil.copytree(sku_dir, dist_dir)


def check_dir_exist(sku_id):
    """
    检查请求图片是否存在
    :param item:
    :return:
    """
    root = settings.get('IMAGES_STORE')
    img_file = root + 'cert/' + sku_id
    if not os.path.exists(img_file):
        return False

    return True


def check_image_exist(item):
    """
    检查请求图片是否存在
    :param item:
    :return:
    """
    root = settings.get('IMAGES_STORE')
    if item and item['image_paths']:
        paths = item['image_paths']
        for path in paths:
            img_file = root + '/' + path
            if not os.path.exists(img_file):
                return False

    return True
